<?php

namespace App\Service\playlet;
use App\Model\Company;
use App\Model\PlayletEpisodes;
use App\Model\PlayletTag;
use App\Service\CommicService;
use App\Model\Playlet;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Utils\ApplicationContext;
use App\Common\Response\SystemCode;
class PlayletService extends CommicService
{
    const cacheDuration = 60 * 15;
    public function __construct()
    {
        $container = ApplicationContext::getContainer();
        $this->redisService = $container->get(\Hyperf\Redis\Redis::class);
    }
    const STATUS_ENABLE  = 1;

    public function search(Array $params){

        $keyword     = $params['keyword'] ?? '';
        $status      = $params['status'] ?? '';
        $company_id      = $params['company_id'] ?? '';
        $pageSize    = $params['pageSize'] ?? 10;
        $page        = $params['page'] ?? 1;

        $query = Playlet::query()->select(['id','name','cover','company_id','introduction','price','rank','is_finish','pay_type','status','created_at','updated_at']);

        if ($keyword) {
            $query->orWhere([['name', 'like', '%'.$keyword.'%']]);
        }
        if ($status != '') {
            $query->where(['status' => $status]);
        }
        if (!empty($company_id)) {
            $query->where(['company_id' => $company_id]);
        }
        $models = $query->orderBy('updated_at','desc')->paginate($pageSize,['*'],'page',$page);
        $items = $models->items();
        $selectData = [];
        foreach ($items as $item){
            $data = $item->toArray();

            if(!empty($item->company)){
                $data['company_name']  = $item->company->name;
            }else{
                $data['company_name']  = '';
            }
            $data['status_name']  = self::$commonStatus[$item->status];
            $playletEpisodesCount = PlayletEpisodes::query()->where(['playlet_id' => $item->id])->count();
            $data['playet_episodes_count'] = $playletEpisodesCount;
            $data['is_finish_name'] = Playlet::$finishStatus[$item->is_finish];
            $data['pay_type_name'] = Playlet::$payType[$item->pay_type];
            $selectData[] =$data;

        }
        $data = $models->toArray();
        $data['data'] = $selectData;
        return $data;
    }

    public function createOrUpdate(Array $postData, bool $is_update = false, Playlet $playletInfo = null){
        $name = $postData['name'];
        $cover = $postData['cover'] ?? '';
        $rank = $postData['rank'] ?? '1';
        $company_id = $postData['company_id'] ?? '';
        $introduction = $postData['introduction'];
        $price = $postData['price'];
        $is_finish = $postData['is_finish'] ?? 1;
        $pay_type = $postData['pay_type'] ?? 1;
        $status = $postData['status'];
        $model = !empty($playletInfo)? $playletInfo : new Playlet();
        $is_check_user = true;
        if($is_update) {
            //修改时判断用户名是否一致
            if ($name == $model->name) {
                $is_check_user = false;
            }
        }
        if($is_check_user){
            $playletInfo = Playlet::query()->where('name',$name)->first();
            if(!empty($playletInfo)){
                return $this->response(SystemCode::SYSTEM_ERROR, '剧集名称已存在');
            }
            $model->name = $name;
        }

        if(!empty($company_id)){

            $companyInfo = Company::query()->where('id',$company_id)->first();
            if(empty($companyInfo)){
                return $this->response(SystemCode::SYSTEM_ERROR, '公司不存在');
            }

        }else{
            $company_id = 0;
        }


        $model->introduction = $introduction;
        $model->price = $price;
        $model->company_id = $company_id;
        $model->rank = $rank;
        $model->is_finish = $is_finish;
        if(!empty($cover)){
            $model->cover = $cover;
        }
        $model->pay_type = $pay_type;
        $model->status = $status;
        if($model->save()){

            return $this->response(SystemCode::SYSTEM_SUCCESS);
        }else{
            return $this->response(SystemCode::SYSTEM_ERROR,'保存错误');
        }
    }

    public function updateTag(Array $postData, Playlet $playletInfo = null){

        $tag_ids = $postData['tag_ids'] ?? [];
        //tag 标签 清空这短剧的所有标签
        PlayletTag::query()->where(['playlet_id' => $playletInfo->id])->delete();
        if(!empty($tag_ids)){
            foreach ($tag_ids as $tag_id){
                PlayletTag::create(
                    [
                        'tag_id'   => $tag_id,
                        'playlet_id'   => $playletInfo->id,
                    ]
                );
            }
        }

        return $this->response(SystemCode::SYSTEM_SUCCESS);
    }

    public function batchUpload(Array $postData,int $playlet_id,$cover){

        $videoData = $postData['videos'];
        $errorMeg = [];
        foreach ($videoData as $videoDatum){

            if(empty($videoDatum['play_url']) || empty($videoDatum['playlet_number'])){
                $errorMeg[] = $videoDatum['video_name'].' 不存在上传视频或者集数出现问题';
                continue;
            }

            $playlet_number = (int)$videoDatum['playlet_number'];
            if(empty($playlet_number)){
                $errorMeg[] = $videoDatum['video_name'].' 集数名称有问题';
                continue;
            }
            $playlet_number_name = $this->numToStr($playlet_number);
            $play_url = $videoDatum['play_url'];
            if(empty($playlet_number_name)){
                $errorMeg[] = $videoDatum['video_name'].' 集数名称有问题';
                continue;
            }
            $playlet_number_name = '第'.$playlet_number_name.'集';
            $selectData = PlayletEpisodes::query()->where(['playlet_id' => $playlet_id,'playlet_number' => $playlet_number])->first();
            if(!empty($selectData)){
                $selectData->playlet_number_name = $playlet_number_name;
                $selectData->play_url = $play_url;
                $selectData->is_upload = 1;
                $selectData->save();
            }else{
               $insertData = new PlayletEpisodes();

                $insertData->playlet_id = $playlet_id;
                $insertData->playlet_number = $playlet_number;
                $insertData->playlet_number_name = $playlet_number_name;
                $insertData->play_url = $play_url;
                $insertData->cover = $cover;
                $insertData->amount = 200;
                $insertData->save();
            }
        }
        if(!empty($errorMeg)){
            return $this->response(SystemCode::SYSTEM_ERROR,implode(',',$errorMeg));
        }else{
            return $this->response(SystemCode::SYSTEM_SUCCESS);
        }
    }
}